package com.sun.showcase.strategy.limit;

import java.util.concurrent.ConcurrentHashMap;

import com.google.common.util.concurrent.RateLimiter;

/**
 * 基于Guava RateLimiter 的分布式限流
 * @author SUN
 *
 */
public class GuavaRateLimitStrategy implements RateLimitStrategy {
	private static final ConcurrentHashMap<String,RateLimiter> limitMap = new ConcurrentHashMap<String,RateLimiter>();

	public GuavaRateLimitStrategy() {
		super();
	}


	@Override
	public boolean doLimit(String key,int rate) {
		RateLimiter limiter = null;
		if(limitMap.containsKey(key)) {
			limiter = limitMap.get(key);
		}else {
			limiter = RateLimiter.create(Double.valueOf(rate));
			limitMap.put(key, limiter);
		}
		return limiter.tryAcquire();
	}

}
